package com.xuliugen.jwt.demo.filter;

import com.xuliugen.jwt.demo.jwt.JwtHelper;
import com.xuliugen.jwt.demo.jwt.TokenState;
import net.minidev.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 校验TOKen
 * @author xuliugen
 * @date 2018/1/19
 */
@WebFilter(filterName = "CheckTokenFilter", urlPatterns = "/*")
public class CheckTokenFilter implements Filter {

    private static Logger logger = LoggerFactory.getLogger(CheckTokenFilter.class);

    @Value("${auth.token.is.open}")
    private Boolean isOpen;

    @Value("${auth.exclude.urls}")
    private String excludeUrl;

    /**
     * 不进行Token认证的url
     */
    private String[] excludeUrls = new String[]{};

    @Override
    public void init(FilterConfig filterConfig) {
        this.excludeUrls = excludeUrl.split(",");
    }

    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //如果配置文件中是默认的打开Token认证
        if (isOpen) {
            //如果是excludeUrls里边的则直接放行
            for (String excludeUrl1 : excludeUrls) {
                if (request.getRequestURI().endsWith(excludeUrl1)) {
                    //登陆接口不校验token，直接放行
                    chain.doFilter(request, response);
                    return;
                }
            }

            /*
             * 其他API接口一律校验token
             */
            logger.info("--------**开始校验token**--------");

            //1、从请求头中获取token
            String authorization = request.getHeader("Authorization");
            String token = null;
            if (authorization != null) {
                token = authorization.split(" ")[1];
            }
            Map<String, Object> resultMap = JwtHelper.validToken(token);
            TokenState state = TokenState.getTokenState((String) resultMap.get("state"));
            if (state == TokenState.VALID) {
                chain.doFilter(request, response);
            } else if (state == TokenState.EXPIRED) {
                logger.info("----------token时间过期----------");
                //token过期或者无效，则输出错误信息返回给 ajax
                JSONObject outputMSg = new JSONObject();
                outputMSg.put("msg", "您的token过期了，请重新登陆");
                output(outputMSg.toJSONString(), response);
            } else if (state == TokenState.INVALID) {
                logger.info("----------无效token----------");
                //token过期或者无效，则输出错误信息返回给ajax
                JSONObject outputMSg = new JSONObject();
                outputMSg.put("msg", "您的token不合法，请重新登陆");
                response.setStatus(HttpStatus.UNAUTHORIZED.value());
                output(outputMSg.toJSONString(), response);
            }
            logger.info("--------**校验token结束**--------");
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }

    private void output(String jsonStr, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=UTF-8;");
        response.setCharacterEncoding("UTF-8");
        ServletOutputStream out = response.getOutputStream();
        out.write(jsonStr.getBytes("UTF-8"));
        out.flush();
        out.close();
    }
}
